<template>
  <div class="collect">
    <navBar :title="query.type === 'foot' ? '我的足迹' : '我的收藏'" />

    <!-- 内容 -->
    <div class="content">
      <van-cell title="" @click="update = !update" :value="!update ? '管理' : '取消'" />

      <!-- 商品列表 -->
      <van-grid :column-num="2">
        <van-grid-item v-for="(item, i) in collectList" :key="i">
          <template #icon>
            <van-checkbox v-model="item.change" v-show="update" />
            <van-image
              width="120px"
              height="100%"
              :src="item.image"
            />
          </template>
          <template #text>
            <div class="text">{{ item.storeName }}</div>
            <div class="price">￥{{ item.price }}</div>
          </template>
        </van-grid-item>
      </van-grid>
    </div>

    <!-- 空状态 -->
    <van-empty description="空空如也" />

    <!-- 删除 -->
    <van-submit-bar v-if="update" button-text="删除" @submit="delCollect">
    <van-checkbox v-model="checked">全选</van-checkbox>
    <div style="flex: 1" />
  </van-submit-bar>
  </div>
</template>

<script>
import {
  collectUser,
  delCollect,
} from '@/api/collect'

export default {
  data() {
    return {
      update: false,
      collectList: [], // 
      query: {}, // 页面参数
      page: {
        page: 1,
        limit: 10,
      }
    }
  },
  created() {
    const { query } = this.$route
    this.query = query
    this.collectUser()
  },
  methods: {
    // 获取收藏或足迹
    async collectUser() {
      const { data } = await collectUser({
        ...this.query,
        ...this.page
      })
      // console.log(JSON.parse(JSON.stringify(data)));
      data?.forEach(item => item.change = false)
      this.collectList = data || []
    },

    // 删除收藏和足迹
    async delCollect() {
      const list = this.collectList?.filter(item => item.change)?.map(item => item.pid)
      if(!list.length) return
      const result = await this.$dialog.confirm({
        title: '提示',
        message: '确认要删除吗',
      }).catch(() => {});
      if(!result) return
      const res = await delCollect({
        ...this.query,
        productIds: list
      })
      if(res.status !== 200) return this.$toast.fail(res.msg)
      this.$toast.success('删除成功~')
      this.collectUser()
    },
  },
  computed: {
    // 全选和全不选
    checked: {
      get() {
        return this.collectList?.reduce(item => item.change) || false
      },
      set(val) {
        this.collectList?.forEach(item => item.change = val)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.collect {
  .content {
    margin: 10px 5px;
    .van-grid {
      text-align: left;
      .van-checkbox {
        position: absolute;
        top: 2px;
        left: 2px;
        z-index: 8;
      }
      .text {
        padding: 0 5px;
      }
      .price {
        width: 100%;
        text-align: left;
        margin-top: 2px;
        padding-left: 10px;
        font-size: 16px;
        color: #ec9860;
      }
    }
  }
}
</style>